package com.admin.kotlintest

import android.Manifest
import android.content.pm.PackageManager
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.SaveListener
import com.admin.bombtest.LoginActivity
import com.admin.kotlintest.activity.HomeActivity
import com.admin.kotlintest.bean.MyUser
import com.socks.library.KLog
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

import java.util.ArrayList

class WelcomeActivity : AppCompatActivity() {

    private val GET_PERMISSION = 0x88
    var index:Int=0

    private var permissions: MutableList<String>? = null

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            1 -> {
                //获取当前登陆的用户数据
                var myuser= BmobUser.getCurrentUser(MyUser::class.java)
                //已有登陆用户，判断用户状态
                myuser?.let {
                    login(myuser)
                }
                //没有登陆用户，跳转到登陆界面
                myuser?:let {
                    startActivity<LoginActivity>()
                    finish()
                }
            }
        }
        false
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_welcome)
        //权限申请判断
        getPermission()
    }

    override fun onResume() {
        super.onResume()
    }

    private fun getPermission() {
        //23版本以上需要动态获取部分权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissions = ArrayList()
            //此处列出的权限必须全部再AndroidManifest中声明
            val needPermissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, //sd卡读取权限
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, //SD卡写权限
                    Manifest.permission.READ_PHONE_STATE, //读取手机状态权限
                    Manifest.permission.ACCESS_FINE_LOCATION,//读取手机位置权限
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.CAMERA,   //相机权限
                    Manifest.permission.RECORD_AUDIO, // 录音，用于语音识别
                    Manifest.permission.ACCESS_NETWORK_STATE)
            val pid = Binder.getCallingPid()
            val uid = Binder.getCallingUid()
            for (permission in needPermissions) {
                if (checkPermission(permission, pid, uid) != PackageManager.PERMISSION_GRANTED) {
                    permissions!!.add(permission)
                }
            }
            if (permissions!!.size > 0) {
                requestPermissions(permissions!!.toTypedArray(), GET_PERMISSION)
            } else {
                //不存在需要申请的权限,继续执行需要执行的方法
                toNextStep()
            }
        } else {
            //不需要获取动态权限,可直接执行需要继续的方法
            toNextStep()
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == GET_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //权限获取成功
                toNextStep()
            } else {
                //权限申请被拒绝
                Toast.makeText(this, "您拒绝了权限的开启,可能会影响部分功能的使用,您可以在权限管理中重新赋予权限", Toast.LENGTH_SHORT).show()
                super.onRequestPermissionsResult(requestCode, permissions, grantResults)
            }
        }
    }

    /**
     * 登陆
     */
    private fun toNextStep() {
        handler.sendEmptyMessageDelayed(1, 2500)
    }

    fun login(myUser: MyUser){
        KLog.d(myUser.toString())
        //根据当前用户查询该用户是否已经被禁止登陆
        var query=BmobQuery<MyUser>()
        query.addWhereEqualTo("username",myUser.username)
        query.findObjects(object :FindListener<MyUser>(){
            override fun done(p0: MutableList<MyUser>?, p1: BmobException?) {
                p1?:let {
                    p0?:let {
                        startActivity<LoginActivity>()
                        finish()
                    }

                    p0?.let {
                        if(p0[0].disabled){
                            toast("你已经被禁止登陆，请联系管理员")
                            startActivity<LoginActivity>()
                            finish()
                        }else{
                            startActivity<HomeActivity>()
                            finish()
                        }
                    }
                }
                p1?.let {
                    startActivity<LoginActivity>()
                    finish()
                }
            }
        })
    }
}
